<template>
  <div>
    <div class="btns">
<!--      <el-button @click="asdasd('a6ebb269649843b5baa351b91db34f76')"></el-button>-->
      <el-button  v-if="verifyRoleType.iskycgly()" type="primary" @click="openDialog"><el-icon class="mr-[5px]">
          <Plus />
        </el-icon>新增 </el-button>
      <el-button v-if="verifyRoleType.isKymsOrkycgly()" @click="handleDeleteS"><el-icon class="mr-[5px]">
          <DeleteFilled />
        </el-icon>删除</el-button>
<!--      <el-button><svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出</el-button>-->
      <!--          <el-button type="primary" icon="Histogram" > 统计分析</el-button>-->
    </div>
    <div v-loading="loading">
      <el-table :data="table" style="width: 100%" @selection-change="handleSelectionChange"
        @sort-change="handleSortChange">
        <el-table-column
            type="selection"
            width="55"
            :selectable="isRowSelectable"
        ></el-table-column>
        <el-table-column label="项目名称">
          <template #default="scope">
            <span @click="JfwbDetailsBtn(scope.row)" class="clickable-status">{{ scope.row.projectName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="chargerName" label="负责人" sortable="p.charger_name"></el-table-column>
        <el-table-column prop="outboundFee" label="申请外拨金额">
          <template #default="scope">
            {{turnWanyuan(scope.row.outboundFee)}}
          </template>
        </el-table-column>
        <el-table-column prop="outbounddate" label="申请外拨日期" sortable="b.outbounddate"></el-table-column>
        <el-table-column prop="unitName" label="所属单位" ></el-table-column>
        <el-table-column sortable="b.checkstatus" prop="checkstatus" label="审核状态">
          <template #default="{ row }">
            <CommonLabel :dataList="checkStatusList" valueKey="dictValue" labelKey="dictLabel"
              :value="row.checkstatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">

            <!-- 科研人员 -->
            <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" plain size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 2" @click="JfwbDetailsBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 1" plain type="warning" size="small" @click="handleCancel(scope.row)">
              撤销
            </el-button>

            <!-- 科研秘书 -->
            <el-button v-if="verifyRoleType.isKyms() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row, '编辑1')">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.isKyms() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" plain size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 1" plain type="primary" size="small" @click="handleEdit(scope.row, '编辑2')">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 1 && scope.row.isAuditor" @click="openauditBtn(scope.row)" plain type="success" size="small">
              审核
            </el-button>
            <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 2" @click="JfwbDetailsBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>

            <!-- 科研管理员 -->
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row, '编辑1')">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" @click="JfwbDetailsBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" plain size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1" plain type="primary" size="small" @click="handleEdit(scope.row, '编辑2')">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1" @click="JfwbDetailsBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1 && scope.row.isAuditor" @click="openauditBtn(scope.row)" plain type="success" size="small">
              审核
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 2" @click="JfwbDetailsBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
<!--            <el-button  @click="openauditBtn(scope.row)">cs查看</el-button>-->



<!--            <el-button v-if="!(verifyRoleType.isKymsOrkycgly() && scope.row.checkstatus == 2)" plain type="primary"  size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
<!--            <el-button  v-if="verifyRoleType.isKyry() && scope.row.checkstatus == '1'" plain type="warning" size="small" @click="handleCancel(scope.row)">撤销</el-button>-->
<!--            <el-button v-if="scope.row.isAuditor"  @click="openauditBtn(scope.row)" plain  type="success" size="small">审核</el-button>-->
<!--            <el-button  v-if="scope.row.checkstatus == -1 || scope.row.checkstatus == 3"  type="danger" plain size="small" @click="handleDelete(scope.row)">删除</el-button>-->
<!--            <el-button v-if="scope.row.checkstatus == 2" @click="JfwbDetailsBtn(scope.row)" plain type="primary"-->
<!--              size="small">查看</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="example-pagination-block">
        <el-pagination layout="->,prev, pager, next, total" :total="total" currentPage1="10"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 引入子组件 -->
    <JfwbDialog ref="dialogRef" :visible="dialogVisible" :projectOptions="projectOptions" :projectInfo="projectInfo"
      :tableData="tableData" @getlist="getList" @save="handleSave" @saveAndPass="handleSaveAndPass"
      @close="dialogVisible = false" @getselectVproject="getselectVproject" />
    <!-- 引入子组件 -->
    <JfwbDialogcompile ref="JfwbDialogcompileRef" :visible="JfwbDialogcompile" :projectOptions="projectOptions"
      :compileRow="compileRow" :tableData="tableData" @getlist="getList" @save="handleSave"
      @saveAndPass="handleSaveAndPass" @close="dialogVisible = false" @getselectVproject="getselectVproject" />
    <!-- 引入子组件 -->
    <JfwbDetails ref="JfwbDetailsRef" :visible="JfwbDialogcompile" :projectOptions="projectOptions"
      :compileRow="compileRow" :tableData="tableData" @getlist="getList" @save="handleSave"
      @saveAndPass="handleSaveAndPass" @close="dialogVisible = false" @getselectVproject="getselectVproject" />
    <audit ref="openaudit" @success="getList">
    </audit>
    <cscs ref="REFcscs"></cscs>
  </div>
</template>

<script setup lang="ts">
const loading = ref(false) // 添加加载状态
//测试
import cscs from '@/components/money/jftzsq.vue'

const REFcscs = ref(null)
const asdasd = function (x){
  //REFcscs.value.openDialogcompile(x)  //经费外拨表
  //REFcscs.value.openjftzsqTable(x)
  REFcscs.value.openDialog(x)  //经费外拨表
}

import { verifyRoleType } from "@/utils/main";
import { ref, defineProps, onBeforeMount, reactive, toRefs } from "vue";
import {turnWanyuan} from "../../../utils/money";
import {
  list,
  selectVproject,
  remove
} from '@/api/money/jfwbApi';
import JfwbDialog from './JfwbDialog.vue'; // 引入子组件
import JfwbDialogcompile from './JfwbDialogcompile.vue';
import {ElMessage, ElMessageBox} from "element-plus"; // 引入子组件
import JfwbDetails from './JfwbDetails.vue';
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useDictFetch from "@/hooks/useDictFetch";
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
//import audit from  './../audit.vue'
import audit from  './../audit.vue'
const openaudit = ref(null)
const openauditBtn = function (row){
  openaudit.value.openaudit(row)
}
const getListParme = defineModel();
const total = ref(0);
const dialogRef = ref(null);
const JfwbDialogcompileRef = ref(null);
const JfwbDetailsRef  = ref(null);
const JfwbDetailsBtn = (row) => {
// 这里可以添加实际的编辑逻辑，比如弹出编辑表单等
  compileRow.value = row;
  JfwbDetailsRef.value.opencompileDialog(row);
}

//获取弹窗项目下拉
// 打开编辑弹窗的方法

// 打开弹窗的方法
const openDialog = () => {
  dialogRef.value.openDialog();
};


//撤销
import { cancelProcess } from "@/api/project/common";
//点击撤销
const handleCancel = async (row) => {
  loading.value = true // 开始加载
  try {
    const res = await cancelProcess(row.processInstanceId);
    if (res.data) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      getList()
    } else {
      ElMessage({
        message: "操作失败！",
        type: "warning",
      });
    }
  } catch (error) {
    console.log(error);
  }finally {
    loading.value = false // 结束加载
  }
};

// 获取表格
const getList = () => {
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitId 从数组转换为字符串
  if (Array.isArray(requestData.unitId)) {
    requestData.unitId = requestData.unitId.join(',');
  }
  list({
    pageNum: 1,
    pageSize: 10,
    ...requestData
  })
      .then((res) => {
        // console.log(getListParme);
        // total.
        total.value = res.total;
        table.value = res.rows
      });
};

onBeforeMount(() => {
  getList();
});

// 分页
const handleCurrentChange = (val: number) => {
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitId 从数组转换为字符串
  if (Array.isArray(requestData.unitId)) {
    requestData.unitId = requestData.unitId.join(',');
  }
  list({
    pageNum: val,
    pageSize: 10,
    ...requestData
  })
      .then((res) => {
        // console.log(getListParme);
        // total.
        total.value = res.total;
        table.value = res.rows
      });
};

// 处理排序变化的方法
// prop：表示当前进行排序的列对应的字段名
// order：表示当前的排序顺序，有三种可能的值：
// 'ascending'：代表正序排序。
// 'descending'：代表倒序排序。
// null：表示取消排序，在当前代码中暂未对该情况进行处理。
const handleSortChange = (row) => {
  getListParme.value.orderByColumn = row.column.sortable;
  getListParme.value.isAsc=row.order;
  getList();
};

// 定义表格数据
const table = ref([]);

// 存储选中的行数据
const selectedProjects = ref([]);

// 处理复选框选择变化的方法
const handleSelectionChange = (val) => {
  selectedProjects.value = val;
  console.log( selectedProjects.value)
};
//批量删除
const handleDeleteS = () => {
  if (selectedProjects.value.length < 1) {
    ElMessage({
      type: 'info',
      message: '请选择删除项',
    })
  } else {
    ElMessageBox.confirm(
      '确认！删除这条数据?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        const idString = selectedProjects.value.map(item => item.id).join(',');
        remove(idString)
          .then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              getList()
            } else {
              ElMessage({
                type: 'info',
                message: res.msg,
              })
            }
          })


      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })

  }
}

const compileRow = ref({})
// 处理编辑操作
const handleEdit = (row) => {
  // 这里可以添加实际的编辑逻辑，比如弹出编辑表单等
  compileRow.value = row;
  JfwbDialogcompileRef.value.opencompileDialog(row);
};

// 处理删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认！删除这条数据?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true // 开始加载
        remove(row.id)
            .then((res)=>{
              if(res.code == 200){
                ElMessage({
                  type: 'success',
                  message: res.msg,
                })
               getList()
              }else {
                ElMessage({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 项目名称下拉框选项
const projectOptions = ref([]);

// 控制弹窗显示与隐藏的变量
const dialogVisible = ref(false);



// 保存按钮点击事件处理函数
const handleSave = (data) => {
  console.log('保存操作', data);
  dialogVisible.value = false;
};

// 保存并通过按钮点击事件处理函数
const handleSaveAndPass = (data) => {
  console.log('保存并通过操作', data);
  dialogVisible.value = false;
};
//判断复选框
const isRowSelectable = (row) => {
  return row.checkstatus!== '1' && row.checkstatus!== '2';
};
// 暴露 getList 方法供父组件调用
defineExpose({
  getList
});
</script>

<style scoped lang="scss">
.btns {
  margin-bottom: 20px;
}
.sss > div {
  margin: 5px 3px;
  width: 100%;
}
.zhi {
  margin: 0 10px;
}
.clickable-status{
  color:#23527c;
}
.clickable-status:hover{
  color:#23527c;
  cursor: pointer;
  text-decoration: underline;
}
</style>